package cn.initcap.algorithm.leetcode;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author initcap
 * @date Created in 2020/1/19 17:01.
 */
public class TreeNodeBuildUtil {

    public static void main(String[] args) {
        Integer[] nums = {5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1};
        TreeNode root = TreeNodeBuildUtil.buildTree(nums);
        System.out.println(root);
    }

    public static TreeNode buildTree(Integer[] nums) {
        if (nums.length == 0) {
            return new TreeNode(0);
        }
        Deque<TreeNode> nodeQueue = new LinkedList<>();
        // 创建一个根节点
        TreeNode root = new TreeNode(nums[0]);
        nodeQueue.offer(root);
        TreeNode cur;
        // 记录当前行节点的数量（注意不一定是2的幂，而是上一行中非空节点的数量乘2）
        int lineNodeNum = 2;
        // 记录当前行中数字在数组中的开始位置
        int startIndex = 1;
        // 记录数组中剩余的元素的数量
        int restLength = nums.length - 1;

        while (restLength > 0) {
            // 只有最后一行可以不满，其余行必须是满的
            for (int i = startIndex; i < startIndex + lineNodeNum; i = i + 2) {
                // 说明已经将nums中的数字用完，此时应停止遍历，并可以直接返回root
                if (i == nums.length) {
                    return root;
                }
                cur = nodeQueue.poll();
                if (nums[i] != null) {
                    cur.left = new TreeNode(nums[i]);
                    nodeQueue.offer(cur.left);
                }
                // 同上，说明已经将nums中的数字用完，此时应停止遍历，并可以直接返回root
                if (i + 1 == nums.length) {
                    return root;
                }
                if (nums[i + 1] != null) {
                    cur.right = new TreeNode(nums[i + 1]);
                    nodeQueue.offer(cur.right);
                }
            }
            startIndex += lineNodeNum;
            restLength -= lineNodeNum;
            lineNodeNum = nodeQueue.size() * 2;
        }

        return root;
    }

    /**
     * 通过有序数组构建二分搜索树
     *
     * @param nums 有序数组
     * @return
     */
    public static TreeNode sortedArrayToBST(int[] nums) {
        if (nums.length == 0) {
            return null;
        }
        return bst(nums, 0, nums.length);
    }

    private static TreeNode bst(int[] nums, int left, int right) {
        if (left == right) {
            return null;
        }
        int center = (right + left) / 2;
        TreeNode root = new TreeNode(nums[center]);
        root.left = bst(nums, left, center);
        root.right = bst(nums, center + 1, right);
        return root;
    }

}
